package com.aliyunlog.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.aliyunlog.model.LogConf;
  
/** 
 * json格式的文件读取类
 *@Author: linqunxuan 
 */  
public class JsonFileReadUtil {  
	
	private static Logger log = Logger.getLogger(JsonFileReadUtil.class);
	
	private static Map<String, LogConf> logConfMap = new HashMap<String, LogConf>();
    
    private static final String FILE_NAME = "jobconf.json";

    public static Map<String, LogConf> getLogConfMap(){
        return logConfMap;
    }

    static {
		try {
			readJsonData(getLogConfStream(FILE_NAME));
		} catch(IOException e){
			throw new RuntimeException("io失败,程序停止执行,喝一波水~这就很舒服",e);
		} catch (Exception e) {
			throw new RuntimeException("json解析失败,程序停止执行,再报错算我输~",e);
		}  
    }
    
    // 获取json配置的文件流
    private static InputStream getLogConfStream(String path){
        LogManager.log(" resource " + JsonFileReadUtil.class.getClassLoader().getResource(""));
    	String pathname=JsonFileReadUtil.class.getClassLoader().getResource("").getPath() + path;
        System.out.println(" path = " + pathname);
        InputStream input = null;
		try {
			input = new FileInputStream(new File(pathname));
		} catch (FileNotFoundException e) {
			throw new RuntimeException("找不到文件: "+ pathname +" 你错任你错,我就不报错~", e);
		}  
		return input;
    }
    
    // 读取日志任务配置
    public static LogConf getLogConf(String confCode){
    	LogConf conf = null;
    	if(MapUtils.isNotEmpty(logConfMap)){
    		conf = logConfMap.get(confCode);
    	}
    	if(conf == null){
    		try {
				readJsonData(getLogConfStream(FILE_NAME));
				
    		} catch(IOException e){
    			new RuntimeException("io失败,程序停止执行");
    		} catch (Exception e) {
    			new RuntimeException("json解析失败,程序停止执行");
    		} 
    	}
    	return conf;
    }



    /** 
     * 从文件读取json数据 
     * @param in 输入流 
     * @throws Exception 
     */  
    public static Map<String, LogConf> readJsonData(InputStream in) throws Exception { 
    	
    	String jsonStr = convertStreamToString(in);
    	
        logConfMap.clear();
        try {  
        	List<LogConf> lists = JSON.parseArray(jsonStr, LogConf.class); 
        	if(CollectionUtils.isNotEmpty(lists)){
            	for (LogConf logConf : lists) {
        			logConfMap.put(logConf.getConfCode(), logConf);
        		}
            	return logConfMap;
        	}else{
        		new RuntimeException("json解析失败没有logConf数组,停止运行");
        	}
        }catch (Exception e){
        	throw new RuntimeException("json解析失败,停止运行");
        }
        return null;
    }  
    
    public static String convertStreamToString(InputStream in) throws UnsupportedEncodingException {      
        /*  
          * To convert the InputStream to String we use the BufferedReader.readLine()  
          * method. We iterate until the BufferedReader return null which means  
          * there's no more data to read. Each line will appended to a StringBuilder  
          * and returned as String.  
          */     
         BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));      
         StringBuilder sb = new StringBuilder();      
     
         String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {      
                 sb.append(line);      
             }      
         } catch (IOException e) {      
             e.printStackTrace();      
         } finally {      
            try {      
                 in.close();      
             } catch (IOException e) {      
                 e.printStackTrace();      
             }      
         }      
     
        return sb.toString();      
     }
    
    /** 
     * @param args 
     */  
    public static void main(String[] args) {
//        System.out.println("lala = " +JsonFileReadUtil.class.getResource("").getPath());
//        System.out.println("xixi = " + JsonFileReadUtil.class.getResource("/").getPath());

         //getJsonData();//读取数据
        Map<String, LogConf> map = null;
		try {
			map = readJsonData(getLogConfStream(FILE_NAME));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println(JSON.toJSONString(map));
    }  
}  
